package io.mqttpush.mqttserver.handles;


import io.mqttpush.common.events.CommonTopics;
import io.mqttpush.common.events.MsgEvent;
import io.mqttpush.common.events.utils.ByteBufEncodingUtil;
import io.mqttpush.mqttserver.msgs.MessageSender;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.mqtt.MqttPublishMessage;
import io.netty.handler.codec.mqtt.MqttQoS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author tianzhenjiu
 * @date 2020/4/28 17:35
 */
public class NoticeHandle extends ChannelInboundHandlerAdapter {

    Logger logger= LoggerFactory.getLogger(getClass());


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if(!(evt instanceof MsgEvent)){
            logger.info("recv the event is not AbstractHandle{}",evt);
            return;
        }


        MsgEvent abEvt=(MsgEvent)evt;

        String eventName=abEvt.eventName();

        MessageSender messageSender=MessageSender.getInstance();


        String topicName= CommonTopics.eventTopic.concat(eventName);

        ByteBuf byteBuf=ByteBufEncodingUtil.getInstance().encodEventCommon(abEvt,ctx.alloc());

        if(byteBuf==null||byteBuf.refCnt()<0){
            return;
        }
        MqttPublishMessage mqttMessage=messageSender.createCommonMqttPublish(MqttQoS.EXACTLY_ONCE,topicName,byteBuf);

        logger.info("send  the event {},{}",topicName, abEvt);

        MessageSender.getInstance().sendMessage(
                NoticeHandle.class.getName(),
                topicName,mqttMessage);

    }
}
